package com.ailanyin.admin.modules.system.service.impl;


import cn.hutool.core.util.StrUtil;
import com.ailanyin.admin.modules.system.mapper.SysBlacklistUserMapper;
import com.ailanyin.admin.modules.system.model.SysBlacklistUser;
import com.ailanyin.admin.modules.system.service.SysBlacklistUserService;
import com.ailanyin.common.constant.UserConstants;
import com.ailanyin.common.service.RedisService;
import com.ailanyin.common.utils.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author ailanyin
 * @version 1.0
 * @since 2021/11/1 0001 下午 15:14
 */
@Service
public class SysBlacklistUserServiceImpl implements SysBlacklistUserService {

    @Autowired
    private RedisService redisService;
    @Resource
    private SysBlacklistUserMapper blacklistUserMapper;

    /**
     * 获取黑名单列表
     *
     * @param blacklistUser blacklistUser
     * @return list
     */
    @Override
    public List<SysBlacklistUser> selectBlackList(SysBlacklistUser blacklistUser) {
        return blacklistUserMapper.selectByParam(blacklistUser);
    }

    /**
     * 批量删除黑名单
     *
     * @param ids ids
     */
    @Override
    public void removeBlacklistUser(List<SysBlacklistUser> ids) {
        List<Long> idList = new ArrayList<>();
        List<String> ipList = new ArrayList<>();
        ids.forEach(
                blacklistUser -> {
                    idList.add(blacklistUser.getId());
                    ipList.add(blacklistUser.getIp());
                });
        blacklistUserMapper.deleteBatchIds(idList);
        // 从缓存中移除
        redisService.sRemove(UserConstants.BLACKLIST_KEY, ipList.toArray());
    }

    /**
     * 新增黑名单
     *
     * @param blacklistUser blacklistUser
     */
    @Override
    public void insertBlacklistUser(SysBlacklistUser blacklistUser) {
        if (StrUtil.isNotBlank(blacklistUser.getIp())) {
            blacklistUser.setAddress(IpUtil.getRealAddressByIp(blacklistUser.getIp()));
        }
        blacklistUser.setCreateTime(new Date());
        blacklistUserMapper.insertBlacklistUser(blacklistUser);
    }

    /**
     * 同步黑名单到缓存
     */
    @Override
    public void addListToCache() {
        List<SysBlacklistUser> blacklistUserList = blacklistUserMapper.selectByParam(new SysBlacklistUser());
        blacklistUserList.forEach(blacklistUser -> redisService.sAdd(UserConstants.BLACKLIST_KEY, blacklistUser.getIp()));
    }
}
